import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/daily_quiz.dart';
import '../../shared/models/word.dart';

import '../../shared/providers/coin_provider.dart';
import '../../shared/providers/quiz_provider.dart';
import '../../data/master_vocabulary.dart';
import 'daily_quiz_result_page.dart';

class DailyQuizPage extends ConsumerStatefulWidget {
  const DailyQuizPage({super.key});

  @override
  ConsumerState<DailyQuizPage> createState() => _DailyQuizPageState();
}

class _DailyQuizPageState extends ConsumerState<DailyQuizPage> with TickerProviderStateMixin {
  late AnimationController _cardAnimationController;
  late AnimationController _progressAnimationController;
  late Animation<double> _cardAnimation;
  late Animation<double> _progressAnimation;
  
  Timer? _autoNextTimer;
  Timer? _quizTimer;
  int? _selectedAnswer;
  bool _showResult = false;
  int _currentQuestionIndex = 0;
  int _correctAnswers = 0;
  List<Word> _questions = [];
  List<List<String>> _allOptions = [];
  List<int> _correctIndexes = [];
  DateTime _startTime = DateTime.now();

  @override
  void initState() {
    super.initState();
    
    _cardAnimationController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    
    _progressAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _cardAnimation = CurvedAnimation(
      parent: _cardAnimationController,
      curve: Curves.easeInOutBack,
    );
    
    _progressAnimation = CurvedAnimation(
      parent: _progressAnimationController,
      curve: Curves.easeOutCubic,
    );
    
    _cardAnimationController.forward();
    _progressAnimationController.forward();
    
    _startTime = DateTime.now();
    _startQuizTimer();
  }

  @override
  void dispose() {
    _cardAnimationController.dispose();
    _progressAnimationController.dispose();
    _autoNextTimer?.cancel();
    _quizTimer?.cancel();
    super.dispose();
  }

  void _startQuizTimer() {
    _quizTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  Future<void> _initializeQuestions(List<String> questionIds) async {
    final questions = <Word>[];
    final allOptions = <List<String>>[];
    final correctIndexes = <int>[];
    
    for (final id in questionIds) {
      final word = MasterVocabulary.allVocabulary.firstWhere((w) => w.id == id);
      questions.add(word);
      
      // 生成选项
      final options = _generateOptions(word);
      allOptions.add(options);
      correctIndexes.add(options.indexOf(word.english));
    }
    
    setState(() {
      _questions = questions;
      _allOptions = allOptions;
      _correctIndexes = correctIndexes;
    });
  }

  List<String> _generateOptions(Word correctWord) {
    final allWords = MasterVocabulary.allVocabulary;
    final wrongWords = allWords.where((word) => 
        word.id != correctWord.id && 
        word.category == correctWord.category).toList();
    
    if (wrongWords.length < 3) {
      wrongWords.addAll(allWords.where((word) => 
          word.id != correctWord.id).toList());
    }
    
    wrongWords.shuffle();
    final selectedWrong = wrongWords.take(3).toList();
    
    final options = <String>[
      correctWord.english,
      ...selectedWrong.map((word) => word.english),
    ];
    
    options.shuffle();
    return options;
  }

  void _onAnswerSelected(int index) {
    if (_selectedAnswer != null) return;

    setState(() {
      _selectedAnswer = index;
      _showResult = true;
    });

    final isCorrect = index == _correctIndexes[_currentQuestionIndex];
    if (isCorrect) {
      _correctAnswers++;
    }

    _autoNextTimer = Timer(const Duration(milliseconds: 1500), () {
      _nextQuestion();
    });
  }

  void _nextQuestion() {
    _autoNextTimer?.cancel();
    
    if (_currentQuestionIndex < _questions.length - 1) {
      _cardAnimationController.reverse().then((_) {
        setState(() {
          _currentQuestionIndex++;
          _selectedAnswer = null;
          _showResult = false;
        });
        _cardAnimationController.forward();
        _progressAnimationController.forward();
      });
    } else {
      _completeQuiz();
    }
  }

  Future<void> _completeQuiz() async {
    _quizTimer?.cancel();
    
    final endTime = DateTime.now();
    final duration = endTime.difference(_startTime);
    final accuracy = _correctAnswers / _questions.length;
    
    final service = ref.read(dailyQuizServiceProvider);
    final today = DateTime.now();
    
    final completedQuiz = DailyQuiz(
      id: 'daily_${today.year}_${today.month}_${today.day}',
      date: today,
      questionIds: _questions.map((q) => q.id).toList(),
      totalQuestions: _questions.length,
      correctAnswers: _correctAnswers,
      accuracy: accuracy,
      duration: duration,
      completedAt: endTime,
      isCompleted: true,
    );
    
    await service.saveDailyQuizResult(completedQuiz);
    
    // 刷新相关的Provider
    ref.invalidate(todayQuizCompletedProvider);
    ref.invalidate(todayQuizProvider);
    
    // 跳转到结算页面
    if (mounted) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => DailyQuizResultPage(
            quiz: completedQuiz,
            totalQuestions: _questions.length,
            correctAnswers: _correctAnswers,
            duration: duration,
            accuracy: accuracy,
          ),
        ),
      );
    }
  }

  void _showSubmitConfirmDialog() {
    final remainingQuestions = _questions.length - _currentQuestionIndex - 1;
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          title: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const FaIcon(
                  FontAwesomeIcons.triangleExclamation,
                  color: Colors.orange,
                  size: 20,
                ),
              ),
              const SizedBox(width: 12),
              const Expanded(
                child: Text(
                  'Submit Early?',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: AppConstants.DARK_BLUE,
                  ),
                ),
              ),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Are you sure you want to submit your quiz early?',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey[700],
                  height: 1.4,
                ),
              ),
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: Colors.orange.withOpacity(0.3),
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const FaIcon(
                          FontAwesomeIcons.circleInfo,
                          color: Colors.orange,
                          size: 16,
                        ),
                        const SizedBox(width: 8),
                        const Text(
                          'Current Progress:',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Colors.orange,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '• Answered: ${_currentQuestionIndex + 1} of ${_questions.length} questions',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[700],
                      ),
                    ),
                    Text(
                      '• Remaining: $remainingQuestions questions',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[700],
                      ),
                    ),
                    Text(
                      '• Current accuracy: ${_currentQuestionIndex == 0 ? 0 : ((_correctAnswers / (_currentQuestionIndex + 1)) * 100).toInt()}%',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[700],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              Text(
                'Remaining questions will be marked as incorrect.',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.red[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(
                'Continue Quiz',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _submitEarly();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.orange,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                elevation: 2,
              ),
              child: const Text(
                'Submit Now',
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  void _submitEarly() {
    // 取消所有定时器
    _autoNextTimer?.cancel();
    _quizTimer?.cancel();
    
    // 直接完成测验，不改变正确答案数量
    // 剩余题目将被视为未回答（错误）
    _completeQuiz();
  }

  @override
  Widget build(BuildContext context) {
    final todayQuizAsync = ref.watch(todayQuizProvider);
    final vipStatus = ref.watch(vipStatusProvider);
    
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (vipStatus.isVip) ...[
              const FaIcon(
                FontAwesomeIcons.crown,
                color: Colors.amber,
                size: 18,
              ),
              const SizedBox(width: 8),
            ],
            Text(vipStatus.isVip ? 'VIP Quiz' : 'Daily Quiz'),
          ],
        ),
        centerTitle: true,
        elevation: 0,
        backgroundColor: vipStatus.isVip ? Colors.amber.shade600 : Colors.purple.shade600,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: vipStatus.isVip
                  ? [
                      Colors.amber.shade600,
                      Colors.orange.shade700,
                    ]
                  : [
                      Colors.purple.shade600,
                      Colors.purple.shade800,
                    ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: IconButton(
              icon: const FaIcon(
                FontAwesomeIcons.flag,
                color: Colors.white,
                size: 18,
              ),
              onPressed: () {
                _showSubmitConfirmDialog();
              },
              tooltip: 'Submit Early',
            ),
          ),
        ],
      ),
      body: todayQuizAsync.when(
        data: (quiz) {
          if (_questions.isEmpty) {
            _initializeQuestions(quiz.questionIds);
            return const Center(child: CircularProgressIndicator());
          }
          
          // 注意：当_currentQuestionIndex >= _questions.length时，
          // _completeQuiz()会被调用并跳转到结算页面，
          // 所以这里不需要_buildCompletionScreen()了
          return _buildQuizContent();
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(
          child: Text('Error: $error'),
        ),
      ),
    );
  }

  Widget _buildQuizContent() {
    final currentWord = _questions[_currentQuestionIndex];
    final options = _allOptions[_currentQuestionIndex];
    
    return Column(
      children: [
        _buildProgressBar(),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                _buildQuestionCard(currentWord),
                const SizedBox(height: 40),
                _buildOptionsGrid(options),
                const SizedBox(height: 20),
                _buildBottomInfo(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildProgressBar() {
    final progress = _questions.isEmpty ? 0.0 : (_currentQuestionIndex + 1) / _questions.length;
    final accuracy = _currentQuestionIndex == 0 ? 0.0 : _correctAnswers / (_currentQuestionIndex + 1);
    final elapsed = DateTime.now().difference(_startTime);
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${_currentQuestionIndex + 1} / ${_questions.length}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
              Text(
                'Time: ${elapsed.inMinutes}:${(elapsed.inSeconds % 60).toString().padLeft(2, '0')}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.purple,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Accuracy: ${(accuracy * 100).toInt()}%',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: AppConstants.PRIMARY_BLUE,
                ),
              ),
              Text(
                'Correct: $_correctAnswers',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: Colors.green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              final vipStatus = ref.watch(vipStatusProvider);
              return LinearProgressIndicator(
                value: progress * _progressAnimation.value,
                backgroundColor: Colors.grey[300],
                valueColor: AlwaysStoppedAnimation<Color>(
                  vipStatus.isVip ? Colors.amber.shade600 : Colors.purple.shade600,
                ),
                minHeight: 6,
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionCard(Word word) {
    return AnimatedBuilder(
      animation: _cardAnimation,
      builder: (context, child) {
        final vipStatus = ref.watch(vipStatusProvider);
        return Transform.scale(
          scale: _cardAnimation.value,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.all(30),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: vipStatus.isVip
                    ? [
                        Colors.amber.shade600.withOpacity(0.9),
                        Colors.orange.shade700,
                      ]
                    : [
                        Colors.purple.shade600.withOpacity(0.9),
                        Colors.purple.shade800,
                      ],
              ),
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: (vipStatus.isVip 
                      ? Colors.amber.shade600 
                      : Colors.purple.shade600).withOpacity(0.3),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              children: [
                const FaIcon(
                  FontAwesomeIcons.brain,
                  color: Colors.white,
                  size: 32,
                ),
                const SizedBox(height: 20),
                Text(
                  word.esperanto,
                  style: const TextStyle(
                    fontSize: 36,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    letterSpacing: 1.2,
                  ),
                ),
                const SizedBox(height: 12),
                Text(
                  '[${word.pronunciation}]',
                  style: const TextStyle(
                    fontSize: 18,
                    color: Colors.white70,
                    fontStyle: FontStyle.italic,
                  ),
                ),
                const SizedBox(height: 20),
                const Text(
                  'Choose the correct English translation:',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildOptionsGrid(List<String> options) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 2.5,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
      ),
      itemCount: options.length,
      itemBuilder: (context, index) {
        return _buildOptionButton(options, index);
      },
    );
  }

  Widget _buildOptionButton(List<String> options, int index) {
    final option = options[index];
    final isSelected = _selectedAnswer == index;
    final isCorrect = index == _correctIndexes[_currentQuestionIndex];
    
    Color backgroundColor = Colors.white;
    Color borderColor = Colors.grey.withOpacity(0.3);
    Color textColor = AppConstants.DARK_BLUE;
    
    if (_showResult && isSelected) {
      if (isCorrect) {
        backgroundColor = Colors.green.withOpacity(0.1);
        borderColor = Colors.green;
        textColor = Colors.green.shade700;
      } else {
        backgroundColor = Colors.red.withOpacity(0.1);
        borderColor = Colors.red;
        textColor = Colors.red.shade700;
      }
    } else if (_showResult && isCorrect) {
      backgroundColor = Colors.green.withOpacity(0.1);
      borderColor = Colors.green;
      textColor = Colors.green.shade700;
    }

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: Material(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(16),
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: _selectedAnswer == null ? () => _onAnswerSelected(index) : null,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: borderColor, width: 2),
            ),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (_showResult && isSelected) ...[
                    FaIcon(
                      isCorrect ? FontAwesomeIcons.check : FontAwesomeIcons.xmark,
                      color: isCorrect ? Colors.green : Colors.red,
                      size: 16,
                    ),
                    const SizedBox(width: 8),
                  ],
                  Flexible(
                    child: Text(
                      option,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: textColor,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomInfo() {
    final vipStatus = ref.watch(vipStatusProvider);
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(
            vipStatus.isVip ? FontAwesomeIcons.crown : FontAwesomeIcons.trophy,
            color: vipStatus.isVip ? Colors.amber : Colors.amber,
            size: 16,
          ),
          const SizedBox(width: 8),
          Text(
            vipStatus.isVip 
                ? 'VIP Unlimited Quiz: Random 100 Questions' 
                : 'Daily Challenge: 100 Questions',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }


} 